package com.example.pwj.ffstudy.ui.zhihu.view;

import android.annotation.SuppressLint;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.example.pwj.ffstudy.R;
import com.example.pwj.ffstudy.base.BaseFragment;
import com.example.pwj.ffstudy.bean.zdaily.ZDailyNewsSection;
import com.example.pwj.ffstudy.bean.zdaily.ZDailyStory;
import com.example.pwj.ffstudy.bean.zdaily.ZDailyTitle;
import com.example.pwj.ffstudy.comm.CommAdapter;
import com.example.pwj.ffstudy.ui.fragment.FmManager;
import com.example.pwj.ffstudy.ui.zhihu.ZhiConst;
import com.example.pwj.ffstudy.ui.zhihu.adapter.ZNewsAdapter;
import com.example.pwj.ffstudy.ui.zhihu.contract.ZNewsContract;
import com.example.pwj.ffstudy.ui.zhihu.di.DaggerZNewsPComponent;
import com.example.pwj.ffstudy.ui.zhihu.presenter.ZNewsPresenter;
import com.example.pwj.ffstudy.util.EventBusUtils;

import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;

/**
 * Created by pwj on 2017/8/22.
 */

public class ZhiFragment extends BaseFragment implements ZNewsContract.View, SwipeRefreshLayout.OnRefreshListener {

    @Inject
    ZNewsPresenter mPresenter;
    @BindView(R.id.recyclerView)
    RecyclerView mRecyclerView;
    @BindView(R.id.srf)
    SwipeRefreshLayout mSrf;
    private ZNewsAdapter mZNewsAdapter;
    private static final int TIME_DELAY = 1000;
    private ZDailyTitle zDailyTitle;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_zhi;
    }

    @Override
    protected void init() {
        DaggerZNewsPComponent.builder()
                .build()
                .inject(this);
        mPresenter.takeView(this);
        zDailyTitle = new ZDailyTitle();
        mSrf.setColorSchemeColors(Color.RED, Color.GREEN, Color.BLUE);
        mSrf.setOnRefreshListener(this);
        initRecyclerView();
        initSwipeRefresh();
    }

    @SuppressLint("NewApi")
    private void initRecyclerView() {
        mZNewsAdapter = new ZNewsAdapter(mContext);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        mRecyclerView.setAdapter(mZNewsAdapter);
        mZNewsAdapter.setOnLoadMoreListener(new CommAdapter.OnLoadMoreListener() {
            @Override
            public void loadMore() {
                mPresenter.loadZDailyNews(true);
            }
        });
        mZNewsAdapter.setOnItemClickListener(new CommAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                ZDailyNewsSection item = mZNewsAdapter.getItem(position);
                if (!item.isHeader) {
                    ZDailyStory zDailyStory = item.t;
                    Bundle bundle = new Bundle();
                    bundle.putInt(ZhiConst.ZHIHU_ID, zDailyStory.getId());
                    FmManager.startAct(ZhiFragment.this, ZNewsDetailFragment.class.getName(), bundle);
                }
            }
        });
        mRecyclerView.addOnScrollListener(mOnScrollListener);
    }

    RecyclerView.OnScrollListener mOnScrollListener = new RecyclerView.OnScrollListener() {
        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
            if (layoutManager instanceof LinearLayoutManager) {
                LinearLayoutManager manager = (LinearLayoutManager) layoutManager;
                int position = manager.findFirstCompletelyVisibleItemPosition();
                ZDailyNewsSection newsSection = mZNewsAdapter.getItem(position);
                if (newsSection.isHeader) {
                    ZDailyNewsSection item = mZNewsAdapter.getItem(position);
                    String title = "";
                    if (dy < 0) {
                        //下滑应该是8月25变到8月26
                        List<ZDailyNewsSection> headers = mZNewsAdapter.getHeaders();
                        int index = getIndex(headers, item.header);
                        ZDailyNewsSection section;
                        if (index > 1) {
                            section = headers.get(index - 1);
                        } else {
                            section = headers.get(0);
                        }
                        title = section.header;
                    } else {
                        title = item.header;
                    }
                    zDailyTitle.setTitle(title);
                    EventBusUtils.post(zDailyTitle);
                }
            }
        }
    };

    /**
     * @param headers 包含头的集合
     * @param header  头的值
     * @return header在headers中的位置
     */
    public int getIndex(List<ZDailyNewsSection> headers, String header) {
        for (int i = 0; i < headers.size(); i++) {
            ZDailyNewsSection newsSection = headers.get(i);
            if (header.equals(newsSection.header)) {
                return i;
            }
        }
        return 0;
    }

    @Override
    public void onLoadZDailyNews(List<ZDailyNewsSection> sections) {
        mZNewsAdapter.setNewData(sections);
    }

    @Override
    public void onLoadMoreZDailyNews(List<ZDailyNewsSection> sections) {
        mZNewsAdapter.loadComplete();
        mZNewsAdapter.addAll(sections);
    }

    @Override
    public void onError() {
        cancelSwpieRefresh();
    }

    @Override
    public void onLoadMoreError() {
        mZNewsAdapter.loadComplete();
        cancelSwpieRefresh();
    }

    @Override
    public void onComplete() {
        cancelSwpieRefresh();
    }

    @Override
    public void onRefresh() {
        mPresenter.loadZDailyNews(false);
    }

    private void initSwipeRefresh() {
        if (mSrf != null) {
            mSrf.setRefreshing(true);
            mSrf.post(new Runnable() {
                @Override
                public void run() {
                    onRefresh();
                }
            });
        }
    }

    private void cancelSwpieRefresh() {
        if (mSrf != null) {
            if (mSrf.isRefreshing()) {
                mSrf.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mSrf.setRefreshing(false);
                    }
                }, TIME_DELAY);
            }
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (mPresenter != null) {
            mPresenter.dropView();
            mPresenter = null;
        }
        mRecyclerView.removeOnScrollListener(mOnScrollListener);
    }
}
